package com.lxl.jwt1.utils;

import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
public class TokenFilter extends OncePerRequestFilter {

    UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {


        String token = request.getHeader("token");


        if (token == null) {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.write("token没有传");
            out.flush();
            out.close();
            doFilter(request,response,filterChain);
            return;
        }

        //校验失败
        try {
            Boolean validate = JwtUtils.validate(token);
        } catch (Exception e) {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.write("{'code':406,'msg':'"+e.getMessage()+"'}");
            out.flush();
            out.close();
            doFilter(request,response,filterChain);
            return;
        }


        Claims claims = JwtUtils.getUserName(token);
        String username = claims.get("username",String.class);
        List<String> menus =  claims.get("menus", ArrayList.class);

//        UserDetails user = userDetailsService.loadUserByUsername(userName);


        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String menu : menus) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(menu);
            authorities.add(simpleGrantedAuthority);
        }


        UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(username,null,authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);



    }
}